<template>
  <div class="image-uploader">
    {{ logoUrl }}
    <el-upload
      v-loading="isLoading"
      class="avatar-uploader"
      action="/api/admin/product/fileUpload"
      :show-file-list="false"
      :on-change="handleProgress"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    >
      <img v-if="logoUrl" :src="logoUrl" alt="上传的图片" class="uploaded-image" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

onMounted(() => {
  // console.log('onMounted')
})
const emit = defineEmits(['update:modelValue'])
const isLoading = ref(false)
const logoUrl = ref('')
watch(
  () => props.modelValue,
  (newValue) => {
    console.log(newValue)
    logoUrl.value = newValue
  },
  {
    immediate: true
  }
)
const handleSuccess = (response: any, file: any) => {
  logoUrl.value = response.data // 假设后端返回的数据结构为 { data: { url: '...' } }
  emit('update:modelValue', logoUrl.value)
}
const handleProgress = () => {
  isLoading.value = false
}
const beforeUpload = (file: any) => {
  isLoading.value = true
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 18

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}
</script>

<style scoped lang="scss">
.uploaded-image {
  width: 178px;
  height: 178px;
  background-size: cover;
}
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #3992ef;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
